""" 

    Twitter.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which takes a list of Ids and returns a list of the 6 most recent
    tweets of all the legislators as a JSON object.
    
    Accepts two parameters:
        ids (required) - comma delimited list of Bioguide Ids
        offset (optional) - used for paging to get records 11-20, 21-30, etc.
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import wsgiref.handlers
import const
import facebook
import base64

from datetime import datetime
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
        
from utils import fbUtil, SunlightUtil, memcacheUtil, textUtil

class MainHandler(webapp.RequestHandler):

    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "tweets":[], "cache": ""}
            
        theIds = self.request.get('ids', default_value=None)
            
        if theIds is not None: 
            newsCount = 10
            newsOffset = int(self.request.get('offset', default_value=0))
            tweets = {}
            TWITTER_URL = "http://wubbahed.com/services/representedby/twitter.php?id="
            legislatorIds = theIds.split(",")
            votes = {}    
            memcache = memcacheUtil()  
            sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
                  
            for legislatorId in legislatorIds:
                
                legislator = sunlight.apicall("legislators.get", {"bioguide_id": legislatorId})
                
                if legislator is not None:
                   
                    twitter_id = legislator["legislator"]["twitter_id"]         
                    legislator_twitter = memcache.getJSONFromCache(TWITTER_URL + twitter_id, None, 300)
                    for tweet in legislator_twitter:
                        try:
                            tempdate = datetime.strptime( tweet["created_at"], "%a %b %d %H:%M:%S +0000 %Y" )
                            tweet["friendly_name"] = const.FRIENDLY_NAME[legislatorId]
                            tweet["bioguide_id"] = legislatorId
                        except TypeError:
                            jsonOutput["result"] = "error"
                            jsonOutput["cache"] = legislator_twitter
                            tempdate = datetime.now()
                            
                        tweets[tempdate] = tweet;
                
            keys = tweets.keys()
            keys.sort(reverse=True)  
            textutil = textUtil();
            if keys is not None:
                if len(keys) < (newsCount+newsOffset):
                    newsCount = len(keys) - newsOffset
                for tweetIndex in range(newsCount):
                    tempObj = {}
                    try:
                        tempdate = datetime.now()
                        tempObj["tweet_id"] = tweets[ keys[tweetIndex+newsOffset] ]["id"]
                        tempObj["twitter_name"] = tweets[ keys[tweetIndex+newsOffset] ]["user"]["screen_name"]
                        tempObj["text"] = tweets[ keys[tweetIndex+newsOffset] ]["text"]
                        tempObj["time"] = textutil.timeAgo(None, None, keys[tweetIndex+newsOffset] )
                        tempObj["name"] = tweets[ keys[tweetIndex+newsOffset] ]["friendly_name"]
                        tempObj["id"] = tweets[ keys[tweetIndex+newsOffset] ]["bioguide_id"]
                    except TypeError:
                        tempdate = datetime.now()
                    jsonOutput["tweets"].append( tempObj );
                    
        else:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = "missing IDs"
                
                       
        self.response.out.write(simplejson.dumps(jsonOutput))    
        
        
def main():
    application = webapp.WSGIApplication([('/fb/tweets', MainHandler)],
                                       debug=True)
    run_wsgi_app(application)
                                       

if __name__ == '__main__':
    main()
